package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.model.mess.app.NewBehaviorDTO.UpdateArticleType;

import java.util.Date;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    //注入mongodb 模板对象
    @Autowired
    MongoTemplate mongoTemplate;

    //注入行为实体查询
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 用户点赞或取消点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDTO dto) {
        // 1. 校验参数
        // 1.1点赞需要登录
        //拿出用户id
        Integer userId = AppThreadLocalUtils.getUser().getId();
        //判断用户id是否存在
        if (userId == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "用户未登录,无法点赞");
        }
        //校验文章id不能为空   使用注解校验 -- @NotNull
        //校验点赞方式 只能是0 或 1  使用注解校验 -- @Range(max=1L)  min 默认是0
        // 2. 根据当前登录用户id查询行为实体对象
        ApBehaviorEntry entry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, dto.getEquipmentId());
        if (entry == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 3. 如果是点赞操作  判断是否已经点过赞
        if (dto.getOperation().shortValue() == 0) {
            ApLikesBehavior apLikesBehavior = mongoTemplate.findOne(Query.query(Criteria.where("operation").is(null))
                    , ApLikesBehavior.class);

            if (apLikesBehavior == null) {
                // 4. 没有点过赞则 向mongo点赞集合中 添加点赞数据
                ApLikesBehavior behavior = new ApLikesBehavior();
                behavior.setArticleId(dto.getArticleId());
                behavior.setType((short) 0);
                behavior.setCreatedTime(new Date());
                behavior.setEntryId(entry.getId());
                behavior.setOperation((short) 0);
                mongoTemplate.insert(behavior);
            }
        }
        if (dto.getOperation().shortValue() == 1) {
            // 5. 如果是取消点赞操作  在mongo点赞集合中 删除对应点赞数据
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("operation").is(0));
            ApLikesBehavior remove = mongoTemplate.findAndRemove(query, ApLikesBehavior.class);
            System.out.println(remove);
        }

        //创建mess对象
        NewBehaviorDTO articleMess = new NewBehaviorDTO();
        //设置类型为点赞 likes
        articleMess.setType(UpdateArticleType.LIKES);
        //设置文章id
        articleMess.setArticleId(dto.getArticleId());
        //判断是否点赞 点赞 add+1  取消点赞 add-1
        articleMess.setAdd(dto.getOperation() == 0 ? 1 : -1);

        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE
                ,JSON.toJSONString(articleMess));
        //点赞发送消息
        log.info("点赞行为发送消息 ===> {}", JSON.toJSONString(articleMess));

        return ResponseResult.okResult();
    }
}
